package com.icebergteam.warfacewidget.core.settings;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import android.content.Context;

import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.utils.Serializable;


abstract public class Settings implements Serializable {
	Properties properties;
	
	public static final String className = Settings.class.getCanonicalName();
		
	Settings()	{
		
	}
	
	protected void init(Context context) {
		boolean isExist = true;
		try {
			context.openFileInput( getPrefFileName());
		} catch (FileNotFoundException e) {
			LogManager.LogE(Settings.className, LogManager.getExecuteMethodName() + " can't read pref file",
					e.getMessage());
			e.printStackTrace();
			isExist = false;
		}
		this.properties = new Properties();
		if (!isExist) {
			reconstruct();
		}
		this.properties.clear();

		FileInputStream fin;
		try {
			fin = context.openFileInput( getPrefFileName());
			this.properties.load(fin);
			fin.close();
		} catch (FileNotFoundException e) {
			LogManager.LogE(Settings.className, LogManager.getExecuteMethodName() + " can't read pref file",
					e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			LogManager.LogE(Settings.className, LogManager.getExecuteMethodName() + " can't read pref file",
					e.getMessage());
			e.printStackTrace();
		}
		
	}
	
	private void reconstruct() {
		try {
			Context context = AppManager.getContext();
			FileOutputStream fos = null;
			fos = context.openFileOutput( getPrefFileName(), Context.MODE_PRIVATE);
			fos.close();
		} catch (FileNotFoundException e) {
			LogManager.LogE(Settings.className,
					LogManager.getExecuteMethodName() + "can't create pref file", e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			LogManager.LogE(Settings.className,
					LogManager.getExecuteMethodName()+ " can't create pref file", e.getMessage());
			e.printStackTrace();
		}
	}
	
	protected String getKey(int resId)	{
		return AppManager.getContext().getString(resId);
	}
	
	public void save() {
	}
	
	public void load() throws Exception {
	}
	
	abstract public String getPrefFileName();
}
